import asyncio
import json
from fastmcp import FastMCP
from dotenv import load_dotenv
from datetime import datetime
from llm_util import llm_gen_damai_tips
from damai_api import search as damai_search, list_cities
from config import MY_MODEL

PROMPT_PATH = "prompts/damai_tips_system.txt"

load_dotenv()

mcp = FastMCP("damai-mcp 🚀")

@mcp.tool()
def ping() -> str:
    return "pong"

@mcp.tool()
async def echo(text: str) -> str:
    return text

@mcp.tool()
async def damai_tips(city: str) -> dict:
    data = damai_search(city_name=city)
    items = data.get("pageData", []) if isinstance(data, dict) else []
    events = []
    for it in items[:10]:
        events.append({
            "id": str(it.get("id", "")),
            "title": it.get("name", ""),
            "category": it.get("ctl", ""),
            "venue": it.get("venue", ""),
            "date": it.get("showTime", ""),
            "min_price": it.get("minPrice", None),
            "url": it.get("detailUrl", ""),
        })
    tips = llm_gen_damai_tips(city=city, events=events, system_prompt_path=PROMPT_PATH)
    result = {
        "city": city,
        "source": "damai-api",
        "fetched_at": datetime.utcnow().isoformat()+"Z",
        "events": events,
        "tips": tips,
    }
    return result

@mcp.tool()
def damai_cities() -> dict:
    return {"model": MY_MODEL, "cities": list_cities()}

def main():
    mcp.run(
        transport="sse",
        host="0.0.0.0",
        port=8000,
        path="/mcp",
        log_level="debug",
    )

if __name__ == "__main__":
    main()
